package com.example.springboottest.example.netty.echo;

import com.example.springboottest.student.model.Student;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

@ChannelHandler.Sharable
public class EchoClientHandler extends
        SimpleChannelInboundHandler<ByteBuf> {
    //连上channel是激活状态，发送小子
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
//        Student student = new Student("001", "张三", 19, "武汉市");
        ctx.writeAndFlush(Unpooled.copiedBuffer("Hello Netty!",
                CharsetUtil.UTF_8));
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) {
//        System.out.println(ByteBufUtil.hexDump(in));
        System.out.println(
                "Client received: " + in.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,
                                Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}